<?php
/**
* Library of commonly-used functions
* @package joiner
**/
    require_once $CFG->dirroot . 'mod/joiner/config.php';
    
    
/**
* Create the menu links used by the joiner add-in, as well as setting the commands for the info / navigation menu
* on the side of the page.
*/
function joiner_pagesetup() {
    
    if ( isloggedin() ) {

        global $_SESSION;
        global $JOINER_CFG;
        global $CFG;
        global $data;
     
     
        // The main page won't pop a context value, they have to go somewhere first.
        if ( defined('context') ) {
            if ( substr(context, 0, 5) <> 'join_') {
                if ( !joiner_userjoined( $_SESSION['userid'] ) ) {
                    // Ask user for information.
                    header("Location: " . $CFG->wwwroot . 'mod/joiner/html/join.php?user=' . $_SESSION['userid']);
                    exit;
                }
            }
        }
     
        // Load additional profile data fields from the config.php file to make sure that joiner fields are shown on the profile page.
        if ( is_array( $data['profile:details'] ) ) {
            $data['profile:details'] = array_merge( $data['profile:details'], $JOINER_CFG->profilefields);
        } else {
            $data['profile:details'] = $JOINER_CFG->profilefields;
        }

        // If this is the first login, then check membership rules.
        if ( !( isset( $_SESSION['joiner_checkmemberships']) & $_SESSION['joiner_checkmemberships'] == true) ) {
            joiner_checkmemberships( $_SESSION['userid'] );
            $_SESSION['joiner_checkmemberships'] = true;
        }
        
    } // Logged in
}

/**
* Test to see if the user has all of the required information
*       Cache value in $_SESSION['joiner_userjoined'] to avoid making a db call for every page.
**/
function joiner_userjoined( $user_ident ) {
    global $CFG;
    global $_SESSION;
    global $JOINER_CFG;

    
    // Check to see if we've already cached this value.
  
    if ( !isloggedin() || ( isset( $_SESSION['joiner_userjoined']) & $_SESSION['joiner_userjoined'] == true) ) {
        return true;
    }
    
    // Find names of variables that we are checking for:
    $i = count( $JOINER_CFG->fields );

    // Build Where clause.
    $sql = "(";    
    foreach ( $JOINER_CFG->fields as $v ) {
        $sql .= "'{$v['name']}',";
    }
    // Remove last , and add closing paren.
    $sql = substr( $sql,0,strlen($sql) - 1) . ")";
    
    $sql = "SELECT count(*) as c FROM {$CFG->prefix}profile_data WHERE " .
            " owner = {$user_ident} AND name IN {$sql}";
            
    $counts = recordset_to_array(
        get_recordset_sql($sql)
        );
		
	// Check
    if ( $counts ) {
        // Iterate
        foreach ($counts as $count) {
            // Return if the correct number of options are present
            $_SESSION['joiner_userjoined'] = ( $count->c == $i );
        }
    } else {
        // Error, reset
        $_SESSION['joiner_userjoined'] = false;
    }
    
    return $_SESSION['joiner_userjoined'];
}
 
/**
* Function called to join the user to a community
**/
function joiner_joincommunity( $user_ident, $community_ident) {

    // Add argument to mysql db.
    $friend = new StdClass;
    $friend->owner = $user_ident;
    $friend->friend = $community_ident;
    $friend->status = 'perm';
     
    insert_record('friends',$friend);

}

/**
*   Function called to make sure that the user is a member of all of the correct communities
**/
function joiner_checkmemberships( $user_ident ) {
    global $CFG;
    global $JOINER_CFG;

    // Retrieve profile data to establish what memberships should be created.
    $sql = "SELECT name, value FROM {$CFG->prefix}profile_data " .
            "WHERE owner = {$user_ident}";
            
    $profile = recordset_to_array(
        get_recordset_sql($sql)
        );

    // Exit if no records have been returned, as there is no point is continuing w/o profile data
    if( !$profile ) {
        return -1;
    }
    
    // Retrieve current memberships.
    //      Later code depends upon indexing by username, don't mess with the field order.
    $sql = "SELECT u.username, u.ident FROM {$CFG->prefix}friends f INNER JOIN {$CFG->prefix}users u " .
            " ON f.friend = u.ident WHERE f.owner = {$user_ident}";
            
    $friends = recordset_to_array(
        get_recordset_sql($sql)
        );
    
    // Make sure that this is an array to avoid triggering later errors
    if( !$friends) {
        $friends = array();
    }
    
	// Check for rule-based membership.
    if ( $JOINER_CFG->community_rules ) {
    
        // Iterate thru each rule to see if it applies.
        foreach ($JOINER_CFG->community_rules as $rule) {
        
            // If there is a key for rule field, and it matches, and they're not a member...
            if( array_key_exists( $rule['field'], $profile ) &
                $profile[ $rule['field'] ]->value == $rule['value'] &
                !array_key_exists( $rule['community'], $friends ) ) {
                // Add to community
                joiner_joincommunity( $user_ident, $rule['id'] );
            }
        }
    }
    
    // Check for required memberships
    foreach ($JOINER_CFG->community_join as $rule) {
        // If they're not a member...
        if( !array_key_exists( $rule['community'], $friends ) ) {
            // Add to community
            joiner_joincommunity( $user_ident, $rule['id'] );
        }
    }
    
    //var_dump( 'check');
}
?>